#include "lus_prase.h"
#include <QDir>


#ifdef Q_OS_WIN
#include<windows.h>
#endif

lus_prase::lus_prase(void)
{
    client_version = "0";
    my_variable_id.clear();
    my_group_id = "0";

    /*定时发送板子信息*/
    timer_bdinfo = new QTimer(this);
    connect(timer_bdinfo, SIGNAL(timeout()), this, SLOT(timer_send_dbinfo()));
    timer_bdinfo->stop();

    QString str;
    get_disk_space__(&str);
}

void lus_prase::init_prase(void)
{

    check_dir();

    read_conf();
}

 lus_prase::~lus_prase()
{



}


 void lus_prase::lus_do_cmd(QString cmd)
 {

    QDomDocument xml;
    xml.setContent(cmd);

    QDomElement rootnode = xml.documentElement();


    /*lus软件系统设置类命令解析*/
    if(rootnode.tagName()== "lus_cmd"){

        QString cmd_body = rootnode.attributeNode("body").value();

        qDebug() << "cmd_body" << cmd_body;

        if(cmd_body == "change_gid"){
            cmd_change_gid(rootnode.attributeNode("para1").value());

        }

        return;
    }


    if(rootnode.tagName() == "init_msg"){

        prase_init_msg(rootnode);
        return;
    }

    if(rootnode.tagName() == "send_file"){

     /*   s_file_md5 =  rootnode.attributeNode("md5").value();
        down_status = DOWN_ING;
        newFileConnect();
        */
        return;
    }

    if(rootnode.tagName() == "version_info"){

        prase_version_info(rootnode);
        return;
    }

    if(rootnode.tagName() == "term_cmd"){

        //prase_terminal_cmd(rootnode);
    }


 }

 void lus_prase::cmd_change_gid(QString paral)
{


     /*读取root节点*/
     QDomElement root_node = xml_document.documentElement();

     qDebug() << root_node.tagName();

     root_node.attributeNode("group_id").setValue(paral);


    xml_file.seek(0);
    QTextStream out(&xml_file);
    out.reset();
    out.setCodec("utf-8");
    xml_document.save(out, 4, QDomNode::EncodingFromTextStream);

    my_group_id = paral;

}


void lus_prase::timer_send_dbinfo()
{

    QString str_bd_inf;
    QString cpu_info,
            disk_info;

   get_cpu_usage__(&cpu_info);
   get_disk_space__(&disk_info);

    str_bd_inf = "<bd_info " ;
    str_bd_inf  += (" id=\""         + my_variable_id + "\"");
    str_bd_inf  += (" group_id=\""   + my_group_id + "\"");
    str_bd_inf  += (" version=\""    + client_version + "\"");

    str_bd_inf  += (" cpu_info=\""   + cpu_info       + "\"");
    str_bd_inf  += (" disk_space=\"" + disk_info      + "\" />");

    lus_bd_info = str_bd_inf;

    emit lus_requst_send(lus_bd_info.toLatin1());
}


void lus_prase::check_dir(void)
{
    QDir dir;

    qDebug()<<"path "<< dir.absolutePath();

    QFile file(":/lus_core/lus_conf.xml");
    file.open(QFile::ReadOnly);
    QByteArray lus_conf=  file.readAll();
    file.close();

    dir.setPath("./lus");

    if(!dir.exists()){

        qDebug() << "mkdir ./lus";
        dir.setPath("./");
        if(!dir.mkdir("lus"))
            qDebug()<<"mkdir ./lus fail";

    }

    dir.setPath("./lus/exec");

    if(!dir.exists()){

        dir.setPath("./lus");
        dir.mkdir("./exec");
        //#添加默认conf文件

         QFile file_out("./lus/lus_conf.xml");
         file_out.open(QFile::WriteOnly);
         file_out.write(lus_conf);
         file_out.close();
    }


    dir.setPath("./lus/down");
    if(!dir.exists()){
        dir.setPath("./lus");
        dir.mkdir("down");

    }

    QFileInfo fi("./lus/lus_conf.xml");

    if(!fi.isFile()){

        QFile file_out("./lus/lus_conf.xml");
        file_out.open(QFile::WriteOnly);
        file_out.write(lus_conf);
        file_out.close();

    }

}

/*修改为全局变量*/
void lus_prase::read_conf(void)
 {

    QFileInfo fi("./lus/lus_conf.xml");

    if(!fi.isFile()){
        qErrnoWarning("read lus config file error\n");
    }

    xml_file.setFileName("./lus/lus_conf.xml");

       if(!xml_file.open(QFile::ReadWrite | QFile::Text))
       {
          qDebug() << "open lus_conf.xml error";

           return;
       }

   // QDomDocument document;
    QString error;
    int row = 0, column = 0;
    if(!xml_document.setContent(&xml_file, false, &error, &row, &column))
    {
        qDebug() << "prase error";

             return;
     }


    /*读取root节点*/
    QDomElement root_node = xml_document.documentElement();

    qDebug() << root_node.tagName();

    client_version = root_node.attributeNode("version").value();
    my_group_id = root_node.attributeNode("group_id").value();

    QString server_addr = root_node.attributeNode("server_ip").value();

    if(server_addr.isEmpty()){

        qDebug() << "please set server ip addr";
        return;
    }

    server_ip = server_addr.left(server_addr.indexOf(":"));
    qDebug() << "server ip: "<< server_ip;

    server_port = server_addr.right(server_addr.size() - server_addr.indexOf(":")-1).toInt();

    qDebug() << server_addr.right(server_addr.size() - server_addr.indexOf(":")-1);
    QDomNodeList child_list = root_node.childNodes();
    qDebug()<< "child nodes = "<<child_list.count();

   /*枚举读取子节点*/
   for(int i=0; i< child_list.count(); i++){

        QDomNode child_node = child_list.item(i);
        QDomElement child_element = child_node.toElement();

        //if(child_element.tagName() == "kernel")prase_kernel_conf(child_element);

        //if(child_element.tagName() == "sys_conf")prase_sys_conf(child_element);
   }




 }

void lus_prase::prase_version_info(QDomElement rootnode)
{

      server_version = rootnode.attributeNode("now_version").value();

     qDebug()<<"server version "<<server_version;

      if(server_version.toInt() > client_version.toInt()){

          QString cmd_str = "<lus_requst";
          cmd_str += (" id=\""        + my_variable_id + "\"");
          cmd_str += (" group_id=\""  + my_group_id    + "\"");
          cmd_str += (" type=\"kernel_down\"");
          cmd_str += "/>";

          emit lus_requst_send(cmd_str.toLatin1());
          qDebug()<< "have a new version";

      }

  }

  /*获取服务器分配的动态ID 启动bd_info 定时器*/
 void lus_prase::prase_init_msg(QDomElement rootnode)
 {

    my_variable_id =  rootnode.attributeNode("id").value();

    //if(!my_variable_id.isEmpty())bdinf_send();

    timer_bdinfo->start(2000);

    qDebug()<< "id = "<<my_variable_id;
    qDebug()<< "now_version = "<<server_version;
 }



 /*执行pack 包*/
void lus_prase::lus_exec_pack(QString fileName)
{
    QString cmd;

#ifdef Q_OS_LINUX
    cmd = "./exec_pack.sh " + fileName;
#endif

#ifdef Q_OS_WIN
    cmd = "./exec_pack.bat " +fileName;
#endif

    QByteArray ba = cmd.toLatin1();
    system(ba.data());

    /*执行结果校验*/

    /*保存新的版本信息*/
    /*QFile file("./lus/lus_conf.xml");
       if(!file.open(QFile::ReadWrite | QFile::Text))
       {
          qDebug() << "open error";

           return;
       }

    QDomDocument document;
    QString error;
    int row = 0, column = 0;
    if(!document.setContent(&file, false, &error, &row, &column))
    {
        qDebug() << "prase error";

             return;
     }

*/
    /*读取root节点*/
    QDomElement root_node = xml_document.documentElement();

    qDebug() << root_node.tagName();

    root_node.attributeNode("version").setValue(server_version);

    xml_file.close();

    //回写xml配置
    xml_file.open(QFile::WriteOnly| QFile::Truncate);
    xml_file.seek(0);
    QTextStream out(&xml_file);
    out.reset();
    out.setCodec("utf-8");
    xml_document.save(out, 4, QDomNode::EncodingFromTextStream);
    xml_file.close();
    client_version = server_version;

    //重新打开xml
    if(!xml_file.open(QFile::ReadWrite | QFile::Text))
       {
          qDebug() << "open lus_conf.xml error";
           return;
       }

}


bool lus_prase::get_cpu_usage__(QString * info)
{


#ifdef Q_OS_LINUX
    static double m_cpu_total__ = 0;
    static double m_cpu_use__ = 0;
    QProcess process;
    process.start("cat /proc/stat");
    process.waitForFinished();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");
    auto lst = str.split(" ");
    if(lst.size() > 3)
    {
        double use = lst[1].toDouble() + lst[2].toDouble() + lst[3].toDouble();
        double total = 0;
        for(int i = 1;i < lst.size();++i)
            total += lst[i].toDouble();
        if(total - m_cpu_total__ > 0)
        {
            //qDebug("cpu rate:%.2lf%%",(use - m_cpu_use__) / (total - m_cpu_total__) * 100.0);
            info->sprintf("cpu rate:%.2lf%%",(use - m_cpu_use__) / (total - m_cpu_total__) * 100.0);
            m_cpu_total__ = total;
            m_cpu_use__ = use;
            return true;
        }
    }
    return false;
#endif

#ifdef Q_OS_WIN

    QSettings *CPU = new QSettings("HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",QSettings::NativeFormat);
     *info = CPU->value("ProcessorNameString").toString();
    delete CPU;

#endif
    return  true;
}


bool lus_prase::get_disk_space__(QString * info)
{

#ifdef Q_OS_LINUX
    QProcess process;
    process.start("df -k");
    process.waitForFinished();
    process.readLine();
    while(!process.atEnd())
    {
        QString str = process.readLine();
        if(str.startsWith("/dev/root"))
        {
            str.replace("\n","");
            str.replace(QRegExp("( ){1,}")," ");
            auto lst = str.split(" ");
            if(lst.size() > 5){

               // qDebug("mnt:%s used:%.0lfMB free:%.0lfMB",lst[5].toStdString().c_str(),lst[2].toDouble()/1024.0,lst[3].toDouble()/1024.0);
                info->sprintf("mnt:%s used:%.0lfMB free:%.0lfMB",lst[5].toStdString().c_str(),lst[2].toDouble()/1024.0,lst[3].toDouble()/1024.0);

            }

        }
    }
#endif

#ifdef Q_OS_WIN

   QString m_diskDescribe = "";
    QFileInfoList list = QDir::drives();
    foreach (QFileInfo dir, list)
    {
        QString dirName = dir.absolutePath();
        dirName.remove("/");
        LPCWSTR lpcwstrDriver = (LPCWSTR)dirName.utf16();
        ULARGE_INTEGER liFreeBytesAvailable, liTotalBytes, liTotalFreeBytes;

        if(GetDiskFreeSpaceEx(lpcwstrDriver, &liFreeBytesAvailable, &liTotalBytes, &liTotalFreeBytes) )
        {
            QString free = QString::number((double) liTotalFreeBytes.QuadPart / (1024*1024*1024), 'f', 1);
            free += "G";
            QString all = QString::number((double) liTotalBytes.QuadPart / (1024*1024*1024), 'f', 1);
            all += "G";

            QString str = QString("%1 %2/%3  ").arg(dirName, free, all);
            m_diskDescribe += str;

       }
    }

    *info = m_diskDescribe;
#endif

    return true;
}



